# encoding:utf-8
import copy
import cv2 as cv
import matplotlib.pyplot as py


filename = './rice.png'
image = cv.imread(filename)#读取图片
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)#图像灰度化处理
_, bw = cv.threshold(gray, 0, 0xff, cv.THRESH_OTSU)#大津算法自动阈值化
cv.imshow("otsu", bw)
element = cv.getStructuringElement(cv.MORPH_ELLIPSE, (3, 3))
#数学形态学开运算减少噪声和米粒的粘连
bw = cv.morphologyEx(bw, cv.MORPH_OPEN, element)

#做个拷贝
seg = copy.deepcopy(bw)
#分割后的轮廓的集合
cnts, hier = cv.findContours(seg, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)

count = 0
#对所有轮廓做循环
print("轮廓数量", len(cnts))
for i in range(len(cnts), 0, -1):
    c = cnts[i-1]
    #计算轮廓的面积

    area = cv.contourArea(c)
    if area < 10:
        continue
    count = count + 1
    print("blob", i, " : ", area)
    x, y, w, h = cv.boundingRect(c)
    #每个米粒的边框画成红色
    cv.rectangle(image, (x, y), (x+w, y+h), (0, 0, 0xff), 1)
    #每个米粒标号
    cv.putText(image, str(count), (x, y), cv.FONT_HERSHEY_PLAIN, 0.5, (0, 0xff, 0))
print("米粒数量：", count)

cv.imshow("src_img", image)
cv.imshow("threshold_img", bw)

cv.waitKey()
cv.destroyAllWindows()